<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="账号" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" />
    </el-form-item>
    <el-form-item label="角色" prop="roleid">
      <el-select
        v-model="roleidx"
        class="m-2"
        placeholder="请选择账号角色"
        size="large"
      >
        <el-option
          v-for="(item, index) in roleList"
          :key="item.objectId"
          :label="item.roleName"
          :value="index"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm"> Create </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import axios from "axios";
import { roleGet, userReg } from "@/api/user";
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
      },
      roleidx: "",
      rules: {
        username: [{ required: true, message: "请填写账号", trigger: "blur" }],
        password: [{ required: true, message: "请填写密码", trigger: "blur" }],
        roleidx: [{ required: true, message: "请填选择角色", trigger: "blur" }],
      },
      roleList: [],
    };
  },
  created() {
    roleGet().then((res) => {
      this.roleList = res.data.results;
    });
  },
  methods: {
    async submitForm() {
      console.log(this.$refs.ruleFormRef);
      let formEl = this.$refs.ruleFormRef; //获取了form表单对象
      if (!formEl) return;
      //触发表单验证
      await formEl.validate((valid, fields) => {
        if (valid) {
          console.log("submit!", this.ruleForm);
          //提取被勾选的角色id与角色名称
          let { roleName, objectId } = this.roleList[this.roleidx];
          userReg({ ...this.ruleForm, roleName, roleid: objectId });
        } else {
          console.log("error submit!", fields);
        }
      });
    },
  },
};
</script>
